package org.chronologger.poppaea.client.widgets;

import org.chronologger.poppaea.client.domain.Location;
import org.chronologger.poppaea.client.utils.HasColor;

import com.google.gwt.event.logical.shared.CloseEvent;
import com.google.gwt.event.logical.shared.CloseHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PopupPanel;

import static org.chronologger.poppaea.client.Chronology.*;

public class LocationWidget extends Composite implements EventAware, HasColor {
	public static final int LOCATION_WIDGET_HEIGHT = 50;
	private Label text;
	private final Location location;
	private HandlerRegistration onEditorCloseRegistration;
	
	public LocationWidget(Location location) {
		this.location = location;
		location.setWidget(this);
		
		text = new Label(location.getName());
		initWidget(text);
		final String width = (LOCATION_PANEL_WIDTH - LOCATION_WIDGET_GAP - LOCATION_WIDGET_GAP) + "px";
		final String height = LOCATION_WIDGET_HEIGHT + "px";
		setSize(width, height);
		text.setSize(width, height);
		text.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
		setStyleName("widget-location");
		
		addEventHandler(Event.ONMOUSEDOWN, EventHandler.doNothing);
		addEventHandler(Event.ONDBLCLICK, new EventHandler() {
			
			@Override
			public void fire(Event event) {
				showEditor();
				
				event.preventDefault();
				event.stopPropagation();
			}
		});
		
		setColor(location.getColor());
	}
	
	public void setColor(String color) {
		location.setColor(color);
		getElement().getStyle().setProperty("backgroundColor", color);
		location.updateOnServer();
	}

	public void addEventHandler(int event, EventHandler handler) {
		EventHandler.addEventHandler(this, event, handler);
	}

	public void removeEventHandler(int event, EventHandler handler) {
		EventHandler.removeEventHandlers(this, event, handler);
	}
	
	@Override
	public void onBrowserEvent(Event event) {
		EventHandler.handleEvent(this, event);
	}

	public String getColor() {
		return location.getColor();
	}
	
	public void showEditor() {
		LocationEditor.getInstance().setLocation(this.location);
		onEditorCloseRegistration = LocationEditor.getInstance().addCloseHandler(
				new CloseHandler<PopupPanel>() {
					public void onClose(CloseEvent<PopupPanel> event) {
						updateFromLocation();
						location.updateOnServer();
						onEditorCloseRegistration.removeHandler();
					}
				});
		
	}
	
	protected void updateFromLocation() {
		text.setText(location.getName());
		setColor(location.getColor());
	}
}